﻿using Manon.Admin.ApplicationCore.Common;
using Manon.Admin.ApplicationCore.Infrastructure;
using Manon.Admin.Web.ApplicationCore.Dtos.News;
using Manon.Admin.Web.ApplicationCore.Entities;
using Manon.Admin.Web.ApplicationCore.Entities.News;
using Manon.Admin.Web.ApplicationCore.Interfaces;
using Manon.Core.IOC;
using Manon.Core.Commons;
using Manon.Repository;
using Manon.Repository.Collections;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Manon.Admin.Web.ApplicationCore.Services
{
    public class NewsService : INewsService
    {

        #region 资讯分类
        public async Task<NewsCategoryOutput> GetNewsCategory(int CategoryId)
        {
            if (CategoryId <= 0) return new NewsCategoryOutput() { Enabled = true };

            var logger = Resolver.GetService<ILogger<NewsService>>();
            try
            {


                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();

                var result = await unitOfWork.GetRepository<NewsCategory>().FindAsync(CategoryId);
                return result.ConvertTo<NewsCategory, NewsCategoryOutput>();
            }
            catch (Exception ex)
            {
                logger.LogError("获取角色信息异常", ex);
                throw;
            }
        }

        public async Task<List<NewsCategoryOutput>> GetNewsCateogryList()
        {
            var logger = Resolver.GetService<ILogger<NewsService>>();
            try
            {
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();

                var result = await unitOfWork.GetRepository<NewsCategory>().GetAllByWhere(n => n.IsDeleted == false).OrderBy(m => m.OrderIndex).ToListAsync();

                return result.ConvertTo<NewsCategory, NewsCategoryOutput>();

            }
            catch (Exception ex)
            {
                logger.LogError("获取角色信息异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存资讯分类
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveNewsCategory(NewsCategoryInput Input)
        {
            var logger = Resolver.GetService<ILogger<RoleService>>();
            try
            {
                var identityUser = Resolver.GetService<IIdentityUser>();
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();
                var repos = unitOfWork.GetRepository<NewsCategory>();
                var result = await repos.FindAsync(Input.Id);
                if (result == null)
                {
                    result = new NewsCategory();
                    result.CategoryName = Input.CategoryName;
                    result.CreateTime = DateTime.Now;
                    result.Enabled = Input.Enabled;
                    result.UpdateTime = DateTime.Now;
                    result.OrderIndex = Input.OrderIndex;
                    result.CreateBy = identityUser.UserId;
                    result.UpdateBy = identityUser.UserId;
                    await repos.InsertAsync(result);
                }
                else
                {
                    result.CategoryName = Input.CategoryName;
                    result.Enabled = Input.Enabled;
                    result.UpdateTime = DateTime.Now;
                    result.OrderIndex = Input.OrderIndex;
                    result.UpdateBy = identityUser.UserId;
                    repos.Update(result);
                }
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                logger.LogError("保存资讯分类异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 设置资讯分类是否可用
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SetNewsCategoryEnabled(int CategoryId, bool Enabled)
        {
            var logger = Resolver.GetService<ILogger<RoleService>>();
            try
            {

                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();

                var role = await unitOfWork.GetRepository<NewsCategory>().FindAsync(CategoryId);
                if (role == null) return null;
                role.Enabled = Enabled;
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("设置成功!");

            }
            catch (Exception ex)
            {
                logger.LogError("设置资讯分类是否可用异常", ex);
                throw;
            }
        }

        #endregion

        #region 资讯
        /// <summary>
        /// 获取资讯
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<NewsOutput> GetNews(int Id)
        {
            if (Id <= 0) return new NewsOutput() { Enabled = true };

            var logger = Resolver.GetService<ILogger<NewsService>>();
            try
            {


                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();

                var result = await unitOfWork.GetRepository<News>().FindAsync(Id);

                return result.ConvertTo<News, NewsOutput>();
            }
            catch (Exception ex)
            {
                logger.LogError("获取资讯异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取资讯列表
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<IPagedList<NewsOutput>> GetNewsPagedList(GetNewsPagedListInput Input)
        {
            var logger = Resolver.GetService<ILogger<NewsService>>();
            try
            {
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();
                var categorys = await unitOfWork.GetRepository<NewsCategory>().GetAll().ToListAsync();

                var result = await unitOfWork.GetRepository<News>()
                    .GetQuery()
                    .WhereIf(!string.IsNullOrEmpty(Input.Keyword), e => e.Title.Contains(Input.Keyword) || e.Keyword.Contains(Input.Keyword) || e.Source.Contains(Input.Keyword) || e.Author.Contains(Input.Keyword))
                    .WhereIf(Input.Enabled.HasValue, e => e.Enabled == Input.Enabled.Value)
                    .WhereIf(Input.CategoryId > 0, e => e.CategoryId == Input.CategoryId)
                    .ToPagedListAsync<NewsOutput, News>(Input);
                if (result != null && result.Items != null)
                {
                    foreach (var item in result.Items)
                    {
                        item.CategoryName = categorys?.Where(n => n.Id == item.CategoryId).FirstOrDefault()?.CategoryName;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError("获取资讯列表异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存资讯 
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SaveNews(NewsInput Input)
        {
            var logger = Resolver.GetService<ILogger<RoleService>>();
            try
            {
                var identityUser = Resolver.GetService<IIdentityUser>();
                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();
                var repos = unitOfWork.GetRepository<News>();
                var result = await repos.FindAsync(Input.Id);
                if (result == null)
                {
                    result = new News();
                    result.AllowComment = Input.AllowComment;
                    result.ArticleAbstract = Input.ArticleAbstract;
                    result.ArticleContent = Input.ArticleContent;
                    result.CategoryId = Input.CategoryId;
                    result.Author = Input.Author;
                    result.CommentEndDate = Input.CommentEndDate;
                    result.CommentStartDate = Input.CommentStartDate;
                    result.ImageUrl = Input.ImageUrl;
                    result.Keyword = Input.Keyword;
                    result.ShortTitle = Input.ShortTitle;
                    result.Source = Input.Source;
                    result.Title = Input.Title;
                    result.Enabled = Input.Enabled;
                    result.CreateTime = DateTime.Now;
                    result.UpdateTime = DateTime.Now;
                    result.OrderIndex = Input.OrderIndex;
                    result.CreateBy = identityUser.UserId;
                    result.UpdateBy = identityUser.UserId;
                    await repos.InsertAsync(result);
                }
                else
                {
                    result.CategoryId = Input.CategoryId;
                    result.AllowComment = Input.AllowComment;
                    result.ArticleAbstract = Input.ArticleAbstract;
                    result.ArticleContent = Input.ArticleContent;
                    result.Author = Input.Author;
                    result.CommentEndDate = Input.CommentEndDate;
                    result.CommentStartDate = Input.CommentStartDate;
                    result.ImageUrl = Input.ImageUrl;
                    result.Keyword = Input.Keyword;
                    result.ShortTitle = Input.ShortTitle;
                    result.Source = Input.Source;
                    result.Title = Input.Title;
                    result.Enabled = Input.Enabled;
                    result.UpdateTime = DateTime.Now;
                    result.OrderIndex = Input.OrderIndex;
                    result.UpdateBy = identityUser.UserId;
                    repos.Update(result);
                }
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("保存成功!");
            }
            catch (Exception ex)
            {
                logger.LogError("保存资讯异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 设置资讯是否可用
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> SetNewsEnabled(int Id, bool Enabled)
        {
            var logger = Resolver.GetService<ILogger<RoleService>>();
            try
            {

                var unitOfWork = Resolver.GetService<IUnitOfWork<AdminDbContext>>();

                var news = await unitOfWork.GetRepository<News>().FindAsync(Id);
                if (news == null) return null;
                news.Enabled = Enabled;
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("设置成功!");

            }
            catch (Exception ex)
            {
                logger.LogError("设置资讯是否可用异常", ex);
                throw;
            }
        }
        #endregion






    }
}
